package com.hugehard.here;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;

/**
 * Use BroadcastReceiver to receive SMS sent from desire HERE! users. Parse SMS text and show Google
 * Map for specific (latitude, longitude).
 *
 * @author andrewpiggy, wingyip
 */
public class SmsReceiver extends BroadcastReceiver {
	
	private final static String TAG = SmsReceiver.class.getSimpleName();

    private static String SMS_RECEIVED_ACTION = "android.provider.Telephony.SMS_RECEIVED";

    public static String LATITUDE = "latitude";
    public static String lONGITUDE = "longitude";

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(SMS_RECEIVED_ACTION)) {
            System.out.println("SMS Received!");
            Bundle bundle = intent.getExtras();
            if (bundle != null) {
                Object[] pdusObj = (Object[]) bundle.get("pdus");
                SmsMessage[] messages = new SmsMessage[pdusObj.length];
                // Get SMS information from Pdu.
                for (int i = 0; i < pdusObj.length; i++) {
                    messages[i] = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
                }
                for (SmsMessage currentMessage : messages) {                	
//                    if (currentMessage.getDisplayOriginatingAddress().equals(
//                            MainActivity.PHONE_NUMBER)) {
                	String originatingAddress = currentMessage.getDisplayOriginatingAddress();
					if ((originatingAddress != null && originatingAddress
							.contains(MainActivity.PHONE_NUMBER))
							|| (MainActivity.PHONE_NUMBER != null && MainActivity.PHONE_NUMBER
									.contains(originatingAddress))) {
                        String currentLocationString = currentMessage.getDisplayMessageBody();
                        double latitude = Double.valueOf(currentLocationString.split(",")[0]);
                        double longitude = Double.valueOf(currentLocationString.split(",")[1]);
                        Intent mIntent = new Intent(context, ShowMapActivity.class);
                        mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        mIntent.putExtra(LATITUDE, latitude);
                        mIntent.putExtra(lONGITUDE, longitude);
                        context.startActivity(mIntent);
                    }
                }
            }
        }
    }
}
